#include "threadPool.h"
int exitPipe[2];
void sigFunc(int signum){
    printf("parent is going to exit!\n");
    write(exitPipe[1],"1",1);
}
#define LOG(msg) log_message(__FUNCTION__, __FILE__, __LINE__, msg)

void log_message(const char *function, const char *file, int line, const char *message) {
    openlog("三组的百度网盘项目", LOG_CONS | LOG_PID, LOG_USER);
    time_t now = time(NULL);
    char timestr[64];
    strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", localtime(&now));
    syslog(LOG_INFO, "[%s] %s:%d %s(): %s", timestr, file, line, function, message);
    closelog();
}
int main(int argc, char *argv[])
{
    // ./sever 192.168.118.128 1234 3
    LOG("服务端上线");
    ARGS_CHECK(argc,4);
    pipe(exitPipe);
    if(fork()!=0){
        close(exitPipe[0]);
        signal(SIGUSR1,sigFunc);
        wait(NULL);
        exit(0);
    }
    int workerNum = atoi(argv[3]);
    threadPool_t threadPool;//这个数据结构里面包含了线程池运行的所有组件
    threadPool.tidArr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    threadPool.workerNum = workerNum;
    pthread_mutex_init(&threadPool.mutex,NULL);
    pthread_cond_init(&threadPool.cond,NULL);
    threadPool.exitflag = 0;

    bzero(&threadPool.taskQueue,sizeof(queue_t));
    makeWorker(&threadPool);
    //bzero(&threadPool.taskQueue,sizeof(queue_t));

    memset(&threadPool.taskQueue,0,sizeof(queue_t));
    int sockfd;
    tcpInit(&sockfd,argv[1],argv[2]);
    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitPipe[0]);

    while(1){
        struct epoll_event readySet[10];
        int readyNum = epoll_wait(epfd,readySet,10,-1);
        for(int i = 0; i < readyNum; ++i){
            if(readySet[i].data.fd == sockfd){
                int netfd = accept(sockfd,NULL,NULL);
                pthread_mutex_lock(&threadPool.mutex);
                Enqueue(&threadPool.taskQueue,netfd);
                printf("master send a task!\n");
                pthread_cond_signal(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
            else if(readySet[i].data.fd == exitPipe[0])
            {
                printf("threadPool is going to exit\n");
                pthread_mutex_lock(&threadPool.mutex);
                printf("get mutex\n");
                threadPool.exitflag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);

                for(int j =0;j<workerNum;j++)
                {
                    pthread_join(threadPool.tidArr[j],NULL);
                    printf("%d worker is exited\n",j);
                    //pthread_exit(NULL);
                }
                printf("all worker is exited\n");
                printf("server is exited\n");
                exit(0);
            }

        }
    }
    return 0;
}